package com.ebelter.bodyfatscale.ui.view;

import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.ebelter.bodyfatscale.R;
import com.ebelter.btlibrary.util.ULog;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;

public class DateView extends LinearLayout implements BtHorizontalScrollView.OnScrollChangedListener {

    private static final String TAG = "DateView";

    private static final int DURATION_SCROLL = 300;
    private int minValue;
    private int maxValue;
    private boolean isShowText;
    private String[] showTexts;

    private int curValue;
    private int preValue;
    private int itemWidth;
    private boolean isActionUp = false;
    private int preIndex = -1;

    @BindView(R.id.hsv_date_view)
    BtHorizontalScrollView mScrollView;
    @BindView(R.id.ll_date_view)
    LinearLayout mLayoutDateView;
    private TextView tvChecked;
    private TextView preTvChecked;

    private Point mPoint = new Point();
    private OnValueChangedListener mListener;
    private List<String> mValues = new ArrayList<>();
    private List<TextView> mTextViews = new ArrayList<>();
    private float defTextSize;
    private int defTextColor;
    private int mTextColorChecked;
    private int preIndexChecked = -1;

    public DateView(Context context) {
        super(context);
    }

    public DateView(Context context, AttributeSet attrs) {
        super(context, attrs);
        View view = LayoutInflater.from(getContext()).inflate(R.layout.layout_date_picker_custom, this, true);
        ButterKnife.bind(view);
//        TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.ScrollSelectDateView);
//        mCurrentType = arr.getInt(R.styleable.ScrollSelectDateView_typeView, 1);

//        tvChecked = view.findViewById(R.id.tv_date_checked);
        mScrollView = view.findViewById(R.id.hsv_date_view);
        mLayoutDateView = view.findViewById(R.id.ll_date_view);

        mScrollView.addOnScrollChangedListener(this);

        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        if (wm != null) {
            wm.getDefaultDisplay().getSize(mPoint);
        }

        mTextColorChecked = getResources().getColor(R.color.line_color);
        itemWidth = (int) getContext().getResources().getDimension(R.dimen.dp60);
    }

    public void initData(int min, int max) {
        if (this.minValue == min && this.maxValue == max) {
            return;
        }
        this.minValue = min;
        this.maxValue = max;
        mValues.clear();
        ULog.i(TAG, "-----limitDate-----min = " + min + ",max = " + max);
        if (isShowText && showTexts != null && showTexts.length > 0) {
            for (int i = 0; i < max; i++) {
                mValues.add(showTexts[i]);
            }
        } else {
            for (int i = min; i < max + 1; i++) {
                mValues.add(String.valueOf(i));
            }
        }
        //TODO 滚动到中央
        initViews();
    }


    public void setValue(int value) {
        int indexChecked = value - minValue;

        ULog.i(TAG, "-----setValue-------itemWidth = " + itemWidth + ", indexChecked = " + indexChecked);

        if (preIndexChecked != indexChecked) {
            // TODO 滚动到中央
            mScrollView.scrollTo((int) (itemWidth * (indexChecked + 0.5f)), 0);
        }
        //scrollTo后，因onScrollChanged可能不响应，所以，需要check
        checkedByIndex(indexChecked);
    }

    private void initViews() {
        if (mLayoutDateView != null && mLayoutDateView.getChildCount() > 0) {
            mLayoutDateView.removeAllViews();
        }
        mTextViews.clear();

        final int count = mValues.size();
        ULog.i(TAG, "------initViews-------count = " + count);
        //头部添加2.5个空白的Item
        int width = (int) getResources().getDimension(R.dimen.dp60);
        int widthHalf = (int) getResources().getDimension(R.dimen.dp30);
        LayoutParams params = new LayoutParams(width, width);
        LayoutParams paramsHalf = new LayoutParams(widthHalf, width);
        View view = new View(getContext());
        mLayoutDateView.addView(view, paramsHalf);
        view = new View(getContext());
        mLayoutDateView.addView(view, params);
        view = new View(getContext());
        mLayoutDateView.addView(view, params);
        //实际选项
        View item = null;
        TextView tv = null;
        for (int i = 0; i < count; i++) {
            item = View.inflate(getContext(), R.layout.item_date_picker_custom, null);
            mLayoutDateView.addView(item);
            tv = item.findViewById(R.id.tv_date);
            tv.setText(mValues.get(i));
            defTextColor = tv.getCurrentTextColor();
            defTextSize = tv.getTextSize();
            mTextViews.add(tv);
        }
        //尾部添加2.5个空白的Item
        view = new View(getContext());
        mLayoutDateView.addView(view, params);
        view = new View(getContext());
        mLayoutDateView.addView(view, params);
        view = new View(getContext());
        mLayoutDateView.addView(view, paramsHalf);
    }

    /**
     * 通过索引选中选项
     *
     * @param indexChecked
     */
    private void checkedByIndex(int indexChecked) {
        if (mValues == null || mValues.isEmpty() || indexChecked < 0 || indexChecked >= mValues.size()) {
            return;
        }
        ULog.i(TAG, "-----checkedByIndex-------indexChecked = " + indexChecked + ", mValues = " + mValues);
        TextView tv = mTextViews.get(indexChecked);

        if (preTvChecked != null) {//之前选中的，置回
            preTvChecked.setTextSize(TypedValue.COMPLEX_UNIT_PX, defTextSize);
            preTvChecked.setTextColor(defTextColor);
        }

        //设置选中
       // tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, defTextSize + 20);
        tv.setTextColor(mTextColorChecked);
        preTvChecked = tv;


        if (preIndexChecked == indexChecked) {
            return;
        }

        preIndexChecked = indexChecked;
//        tvChecked.setText(mValues.get(indexChecked));
        curValue = indexChecked + minValue;
        if (mListener != null) {
            mListener.onValueChanged(indexChecked + minValue);
        }
    }


    public int getValue() {
        return curValue;
    }

    public void setShowTexts(String[] showTexts) {
        this.showTexts = showTexts;
        this.isShowText = true;
    }

    public void setOnValueChangedListener(OnValueChangedListener listener) {
        this.mListener = listener;
    }

    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
//        ULog.i(TAG, "-----onScrollChanged-------l = " + l + ", t = " + t + ", oldl = " + oldl + ", oldt = " + oldt);

        float indexF = l * 1.0f / itemWidth;


        int index = (int) indexF;
        if (preIndex != index) {
            ULog.i(TAG, "-----onScrollChanged-------index = " + index);
            if (index >= 0 && index < mValues.size()) {
                checkedByIndex(index);
                preIndex = index;
            }
        }


    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                isActionUp = false;
                break;
            case MotionEvent.ACTION_UP:
                isActionUp = true;
                break;
        }

        return super.onTouchEvent(event);
    }


    public interface OnValueChangedListener {
        void onValueChanged(int value);
    }

}
